<template>
  <!-- tab切换菜单 -->
  <view class="tabs-box flex flex-dir-c">
    <!-- tabs标题 -->
    <u-sticky
      :offset-top="offTop"
      :h5-nav-height="2"
      bg-color="none"
      @fixed="tabTop = true"
      @unfixed="tabUnfixed"
    >
      <view :class="['tabs-content', tabTop ? 'tab-top-m-0' : 'tab-top-m-24']">
        <view class="tab-sticky">
          <!-- tabs标签 -->
          <u-tabs
            :list="titleTabs"
            :duration="0.3"
            :is-scroll="false"
            :current="current"
            active-color="#FBB000"
            :bar-width="90"
            @change="tabsChange"
          ></u-tabs>

          <!-- 下拉筛选 -->
          <view class="filter-box">
            <!-- 特供车源 -->
            <view v-show="swiperCurrent === 0" class="down-sticky">
              <car-source-filter
                @change="filterCarListChange"
                @open="filterOpen"
              ></car-source-filter>
            </view>

            <!-- 最新寻车 -->
            <view v-show="swiperCurrent === 1" class="down-sticky">
              <find-car-filter
                @change="filterFindCarListChange"
                @open="filterOpen"
              ></find-car-filter>
            </view>

            <!-- 车品 - 精品特供 -->
            <view v-show="swiperCurrent === 2" class="down-sticky">
              <car-goods-filter
                :category-list="carGoodsCategoryList"
                @change="filterCarGoodsListChange"
                @open="filterOpen"
              ></car-goods-filter>
            </view>

            <!-- 配件询价 -->
            <view v-show="swiperCurrent === 3" class="down-sticky">
              <accessory-filter
                @change="accessoryFilterListChange"
                @open="filterOpen"
              ></accessory-filter>
            </view>
          </view>
        </view>
      </view>
    </u-sticky>

    <!-- tabs内容列表 -->
    <view :class="['goods-list', tabTop ? 'tab-top-m-0' : 'tab-top-m-24']">
      <swiper :current="swiperCurrent" :duration="300" @change="listSwitch" class="swiper-box">
        <!-- 特供车源 -->
        <swiper-item v-if="['CarStore', 'Factory'].includes(this.auth)">
          <scroll-view :scroll-y="tabTop" show-scrollbar :scroll-into-view="scrollTop" class="swiper-item" @scrolltolower="listScrolltolower">
            <view id="scrollTop"></view>
            <!-- 列表 -->
            <carCard :carList="carList"></carCard>
            <u-loadmore :status="car.status" margin-top="20" margin-bottom="40" @loadmore="clickLoadMore" />
          </scroll-view>
        </swiper-item>

        <!-- 最新寻车 -->
        <swiper-item v-if="['CarStore', 'Factory'].includes(this.auth)">
          <scroll-view :scroll-y="tabTop" show-scrollbar :scroll-into-view="scrollTop" class="swiper-item" @scrolltolower="listScrolltolower">
            <view id="scrollTop"></view>
            <!-- 列表 -->
            <carSourceCard :carList="newCarList"></carSourceCard>
            <u-loadmore :status="newCar.status" margin-top="20" margin-bottom="40" @loadmore="clickLoadMore" />
          </scroll-view>
        </swiper-item>

        <!-- 车品特供 -->
        <swiper-item v-if="['CarStore', 'RepairStore'].includes(this.auth)">
          <scroll-view :scroll-y="tabTop" show-scrollbar class="swiper-item" @scrolltolower="listScrolltolower">
            <!-- 列表 -->
            <carBeauty :carList="goodsList"></carBeauty>
            <u-loadmore :status="goods.status" margin-top="20" margin-bottom="40" @loadmore="clickLoadMore" />
          </scroll-view>
        </swiper-item>

        <!-- 配件询价 -->
        <swiper-item v-if="['CarStore', 'RepairStore'].includes(this.auth)">
          <scroll-view :scroll-y="tabTop" show-scrollbar class="swiper-item" @scrolltolower="listScrolltolower">
            <!-- 列表 -->
            <fittings-card :carList="accessList"></fittings-card>
            <u-loadmore :status="access.status" margin-top="20" margin-bottom="40" @loadmore="clickLoadMore" />
          </scroll-view>
        </swiper-item>
      </swiper>
    </view>
  </view>
</template>

<script>
// 下拉筛选菜单组件
import carSourceFilter from '@/components/down-filters/car-source-filter.vue'
import findCarFilter from '@/components/down-filters/find-car-filter.vue'
import carGoodsFilter from '@/components/down-filters/car-goods-filter.vue'
import accessoryFilter from '@/components/down-filters/accessory-filter.vue'

// 商品列表卡片组件
import carCard from '@/components/card/car-card.vue'
import carSourceCard from '@/components/card/carSource-card.vue'
import carBeauty from '@/components/card/carbeauty-list-item.vue'
import fittingsCard from '@/components/card/fittings-card.vue'

export default {
  name: 'carStoreList',
  components: {
    carSourceFilter,
    findCarFilter,
    carGoodsFilter,
    accessoryFilter,

    carCard,
    carSourceCard,
    carBeauty,
    fittingsCard,
  },
  props: {
    auth: {
      type: String,
      default: '',
    },
		offTop: {
			type:Number,
			required:true
		}
  },
  data() {
    return {
      // tabs切换
      titleTabs: [
        {
          name: '特供车源',
          id: 0,
        },
        {
          name: '最新寻车',
          id: 1,
        },
        {
          name: '车品特供',
          id: 2,
        },
        {
          name: '配件询价',
          id: 3,
        },
      ],
      current: 0, // tabs组件的current值，表示当前活动的tab选项
      tabTop: false, // tab吸顶时触发的开关
      scrollTop: 'scrollTop', // 列表区域滚动条位置id
      statusBarHeight: 0,

      stickyJudgment: false, //筛选置顶判断
      swiperCurrent: 0, // swiper组件的current值，表示当前那个swiper-item是活动的
      /* --------------------------- */
      //特供车源
      carList: [],

      //最新寻车列表
      newCarList: [],

      //车品列表
      goodsList: [],
      carGoodsCategoryList: [], // 车品分类列表

      //寻配件列表
      accessList: [],

      //特供车源筛选
      carId: '', //品牌id
      priceId: '', //价格排序id
      typeId: '', //商家类型id
      addressId: '', //地址id

      //最新寻车筛选
      findCarVersion: '', // 寻车类型
      findCarBid: '', // 寻车品牌id
      findCarAddressId: '', // 寻车地址id

      // 车品特供筛选
      carGoodsCategory: '', // 车品分类-类型
      carGoodsSort: 0, // 车品排序条件

      //寻配件筛选
      accessoryBid: '', //寻配件品牌id
      accessoryType: '', //寻配件类型
      accessoryRegionId: '', //寻配件地区id
      accessoryOrderBy: 0, //寻配排序

      // 不同tabs列表的配置
      // 特供车源
      car: {
        totalHeight: 666,
        numHeight: 230,
        pageNow: 1,
        status: 'loadmore'
      },
      // 最新寻车
      newCar: {
        totalHeight: 666,
        numHeight: 537,
        pageNow: 1,
        status: 'loadmore'
      },
      // 精品特供
      goods: {
        totalHeight: 666,
        numHeight: 464,
        pageNow: 1,
        status: 'loadmore'
      },
      // 配件询价
      access: {
        totalHeight: 666,
        numHeight: 592,
        pageNow: 1,
        status: 'loadmore'
      },
      listHeight: 700, // swiper列表默认高度
      // status: 'loadmore',
      // 根据不同tab请求列表
      CarStoreApi: new Map(),
			cardList:[]
    }
  },

  onLoad() {},

  created() {
    this.statusBarHeight = uni.getSystemInfoSync().statusBarHeight
    // this.tabTop = 128 + this.statusBarHeight
    this.init()
    this.setTabs()
		this.GetCarBrandList()
    // this.getBrandDataGroup()
  },

  methods: {
    // 根据权限获取对应的请求
    init() {
      switch(this.auth) {
        case 'CarStore':
          // 赋值权限对应的请求方法
          this.CarStoreApi.set(0, this.getCarList)
          this.CarStoreApi.set(1, this.getFindCarList)
          this.CarStoreApi.set(2, this.GetGoodList)
          this.CarStoreApi.set(3, this.GetFindGoodList)
          this.getCarList()
          this.getCategoryList()
          break
        case 'Factory':
          // 赋值权限对应的请求方法
          this.CarStoreApi.set(0, this.getCarList)
          this.CarStoreApi.set(1, this.getFindCarList)
          this.getCarList()
          break
        case 'RepairStore':
          // 赋值权限对应的请求方法
          this.CarStoreApi.set(0, this.GetGoodList)
          this.CarStoreApi.set(1, this.GetFindGoodList)
          this.GetGoodList()
          break
      }
      
      // 获取权限请求列表
      // this.permiousList.get(this.auth).get(0)()
      // this.currentApi = this.permiousList.get(this.auth)
    },
    
    // 根据权限设置tabs切换项
    setTabs() {
      let CarStore = [
        {
          name: '特供车源',
          id: 0,
        },
        {
          name: '最新寻车',
          id: 1,
        },
        {
          name: '车品特供',
          id: 2,
        },
        {
          name: '配件询价',
          id: 3,
        },
      ]
      let Factory = [
        {
          name: '特供车源',
          id: 0
        },
        {
          name: '最新寻车',
          id: 1
        }
      ]
      let RepairStore = [
        {
          name: '车品特供',
          id: 1
        },
        {
          name: '配件询价',
          id: 2
        }
      ]
      let tabsMap = new Map([
        ['CarStore', CarStore],
        ['Factory', Factory],
        ['RepairStore', RepairStore],
      ])
      this.titleTabs = tabsMap.get(this.auth)
    },

    // 获取列表数据
    getDataList() {
      console.log('当前', this.swiperCurrent)
      this.CarStoreApi.get(this.swiperCurrent)() // 发起当前tab列表请求
    },

    // 加载前、中、后
    moreStatus(status, i) {
      switch (i) {
        case 0:
          this.car.status = status
          break
        case 1:
          this.newCar.status = status
          break
        case 2:
          this.goods.status = status
          break
        case 3:
          this.access.status = status
          break
      }
    },

    // 选择排序排序置顶
    tapscroll: function () {
      // #ifndef H5
      const query = uni.createSelectorQuery().in(this.$parent)
      query
        .select('.top-section-box')
        .boundingClientRect((data) => {
          console.log('得到布局位置信息', data)
          console.log('节点离页面顶部的距离为' + data.top)
          // 获取节点到顶部的距离
          uni.pageScrollTo({
            duration: 300,
            scrollTop: data.height - this.statusBarHeight - 60 + 110,
          })
        })
        .exec()
      // #endif

      // #ifdef H5
      uni.pageScrollTo({
        duration: 300,
        scrollTop: 680 - this.statusBarHeight,
      })
      // #endif
      this.stickyJudgment = true
    },

    //特供车源
    async getCarList() {
      try {
        // 找出当前内容在tab标题的下标位置
        let index = this.titleTabs.findIndex(s => s.name === '特供车源')
        this.moreStatus('loading', index)
        
        let data = {
          PageIndex: this.car.pageNow,
          PageSize: 10,
          BrandId: this.carId,
          RegionId: this.addressId,
          StoreType: this.typeId !== 1 ? this.typeId : '',
          OrderType: this.priceId,
        }
        const res = await this.$api.common.getCarList(data)
				this.carList = [...this.carList, ...res.data.list]
				console.log(this.cardList, '特供111')
        
        this.moreStatus(res.data.list.length < 10 ? 'nomore' : 'loadmore', index)
        if (res.data.list.length === 0) return false
        this.car.pageNow += 1 // 当前页加1
      } catch (e) {
        console.log(e)
      }
    },

    //最新寻车
    async getFindCarList() {
      try {
        // 找出当前内容在tab标题的下标位置
        let index = this.titleTabs.findIndex(s => s.name === '最新寻车')
        this.moreStatus('loading', index)
  
				let data={
				  'pageIndex': this.newCar.pageNow,
				  'pageSize': 10,
				  'search':'',
				  'brand': this.findCarBid,
				  'specification':this.findCarAddressId ? Number(this.findCarAddressId):0,
				  'region_Limit_Id': this.findCarVersion,
				  'store_Id': this.$store.state.userInfoDetail.store.storeId
				}
        const res =  await this.$api.findCar.GetCarFindBList(data)
				res.data.list.forEach(it => {
				  it.facade_Picture.forEach(item => {
				    if(item.inColour){
				      item.inColour.neiColor=item.inColour.colorCoding?item.inColour.colorCoding.split('/'):[]
				    }
				    if(item.outerColour){
						  item.outerColour.neiColor=item.outerColour.colorCoding?item.outerColour.colorCoding.split('/'):[]
				    }
				  })
				})
        this.newCarList = [...this.newCarList, ...res.data.list]
        this.moreStatus(res.data.list.length < 10 ? 'nomore' : 'loadmore', index)
        if (res.data.list.length === 0) return false
        this.newCar.pageNow += 1 // 当前页加1
      } catch (e) {
        console.log(e)
      }
    },
    // 车品特供 - 精品
    async GetGoodList() {
      try {
        // 找出当前内容在tab标题的下标位置
        let index = this.titleTabs.findIndex(s => s.name === '车品特供')
        this.moreStatus('loading', index)
        
        let data = {
          pageIndex: this.goods.pageNow,
          pageSize: 10,
          content: '',
          type_Id: this.carGoodsCategory,
          sorting: this.carGoodsSort,
          lat: this.$store.state.latitude || 104.063364, //经度
          lon: this.$store.state.longitude || 30.566, //纬度
        }
        const res = await this.$api.common.GetGoodList(data)
        this.goodsList = [...this.goodsList, ...res.data.list]
        this.moreStatus(res.data.list.length < 10 ? 'nomore' : 'loadmore', index)
        if (res.data.list.length === 0) return false
        this.goods.pageNow += 1 // 当前页加1
        console.log(res.data.list, '车品特供')
      } catch (e) {
        console.log(e)
      }
    },
    // 配件询价
    async GetFindGoodList() {
      try {
        // 找出当前内容在tab标题的下标位置
        let index = this.titleTabs.findIndex(s => s.name === '配件询价')
        this.moreStatus('loading', index)
        
        let data = {
          pageSize: 10,
          pageIndex: this.access.pageNow, //页码
          keyWords: '', //搜索关键字
          configuration_Id: this.accessoryBid, //搜索品牌
          partCategoryId: this.accessoryType, //配件类目id
          baseRegionId: this.accessoryRegionId, //市级id
          lat: this.$store.state.latitude
            ? this.$store.state.latitude
            : 104.063364, //经度
          lon: this.$store.state.longitude ? this.$store.state.lon : 30.566, //纬度
          sort: this.accessoryOrderBy,
        }
        const res = await this.$api.accessory.getCarPartListPaged(data)

        this.accessList = [...this.accessList, ...res.data.list]
        this.moreStatus(res.data.list.length < 10 ? 'nomore' : 'loadmore', index)
        if (res.data.list.length === 0) return false
        this.access.pageNow += 1 // 当前页加1
        console.log(res.data.list, '配件')
      } catch (e) {
        console.log(e)
      }
    },

    // 获取分类列表
    async getCategoryList() {
      try {
        let data = {
          pageIndex: 1,
          pageSize: 100,
        }
        const res = await this.$api.carGoods.GetGoodsCarSupplieTypeListPaged(
          data
        )
        this.carGoodsCategoryList = res.data.list.map((item) => ({
          label: item.name,
          value: item.id,
        }))
      } catch (e) {
        //
      }
    },
		// 品牌接口请求
		async GetCarBrandList() {
		  try {
		    const res = await this.$api.common.GetCarBrandList()
		    this.Brandlist = res.data
		    this.$store.commit('setCarBrandList', res.data)
		    console.log(res.data, '品牌')
		  } catch (err) {
		    console.log(err)
		  }
		},

    // 加载更多
    clickLoadMore() {
      let i = this.swiperCurrent
      this.CarStoreApi.get(i)() // 发起当前tab列表请求
    },

    // 切换订单tab
    tabsChange(index) {
      this.swiperCurrent = index
      this.current = index
    },

    /*
     * 特供车源 - 筛选方法
     */

    // 筛选特供车源列表
    filterCarListChange({ type, id }) {
      // type: 0是品牌，1是地区，2是商家类型
      switch (type) {
        case 0:
          this.carId = id
          break
        case 1:
          this.addressId = id
          break
        case 2:
          this.typeId = id[0]
          this.priceId = id[1]
          break
      }
      this.car.pageNow = 1
      this.carList = [] // 清空车源列表
      this.CarStoreApi.get(this.swiperCurrent)()
    },

    /*
     * 最新寻车 - 筛选方法
     */

    filterFindCarListChange({ type, id }) {
      // type: 0是品牌，1是全部类型，2是地区
      switch (type) {
        case 0:
          this.findCarBid = id
          break
        case 1:
          this.findCarAddressId =id
          break
        case 2:
          this.findCarVersion = id
          break
      }
      this.newCar.pageNow = 1
      this.newCarList = [] // 清空寻车列表
      this.CarStoreApi.get(this.swiperCurrent)()
    },

    // 车品特供 - 筛选方法
    // 筛选车品列表
    filterCarGoodsListChange({ type, id }) {
      // type: 0是分类，1是排序
      switch (type) {
        case 0:
          this.carGoodsCategory = id
          break
        case 1:
          this.carGoodsSort = id
          break
      }
      this.goods.pageNow = 1
      this.goodsList = [] // 清空寻车列表
      this.CarStoreApi.get(this.swiperCurrent)()
    },

    // 配件询价 - 筛选方法
    // 筛选配件列表
    accessoryFilterListChange({ type, id }) {
      // type: 0是品牌，1是全部类型，2是地区，3是排序
      switch (type) {
        case 0:
          this.accessoryBid = id + ''
          break
        case 1:
          this.accessoryType = id ? id + '' : ''
          break
        case 2:
          this.accessoryRegionId = id
          break
        case 3:
          this.accessoryOrderBy = id
          break
      }
      this.access.pageNow = 1
      this.accessList = [] // 清空寻车列表
      this.CarStoreApi.get(this.swiperCurrent)()
    },

    // 监听切换完tab的列表
    listSwitch(e) {
      let i = e.detail.current
      this.swiperCurrent = i
      this.current = i

      let st = {}
      switch(this.auth) {
        case 'CarStore':
          st = {
            0: {
              length: this.carList.length,
              height: this.car.totalHeight,
            },
            1: {
              length: this.newCarList.length,
              height: this.newCar.totalHeight,
            },
            2: {
              length: this.goodsList.length,
              height: this.goods.totalHeight,
            },
            3: {
              length: this.accessList.length,
              height: this.access.totalHeight,
            },
          }
          break
        case 'Factory':
          st = {
            0: {
              length: this.carList.length,
              height: this.car.totalHeight,
            },
            1: {
              length: this.newCarList.length,
              height: this.newCar.totalHeight,
            },
          }
          break
        case 'RepairStore':
          st = {
            0: {
              length: this.goodsList.length,
              height: this.goods.totalHeight,
            },
            1: {
              length: this.accessList.length,
              height: this.access.totalHeight,
            },
          }
          break
      }
      if (st[i].length === 0) {
        this.car.pageNow = 1
        this.newCar.pageNow = 1
        this.goods.pageNow = 1
        this.access.pageNow = 1
        this.CarStoreApi.get(i)()
      }
    },

    // 列表滚动到底部触发, 加载更多
    listScrolltolower() {
      let statusMap = new Map([
        [0, this.car],
        [1, this.newCar],
        [2, this.goods],
        [3, this.access],
      ])
      let i = this.swiperCurrent
      // 如果列表底部状态为：加载更多-loadmore，则请求
      if (statusMap.get(i).status === 'loadmore') {
        this.CarStoreApi.get(this.swiperCurrent)()
      }
    },
    
    // 取消吸顶时触发
    tabUnfixed() {
      this.scrollTop = 'scrollTop'
      this.tabTop = false
    },
    
    // 筛选下拉菜单打开时
    filterOpen() {
      if (this.tabTop) return
      uni.pageScrollTo({
        scrollTop: 10000,
        duration: 100
      })
    }
  },
}
</script>

<style lang="scss" scoped>
.tabs-box {
  width: 100%;
  height: 100%;

  /* #ifndef H5 */
  // height: 100vh;
  /* #endif */

  /* #ifdef H5 */
  // height: calc(100vh - 102rpx);
  /* #endif */

  // 左右边距，吸顶时改变边距
  .tab-top-m-0 {
    width: 100%;
    // margin: 0;
  }
  .tab-top-m-24 {
    width: 702rpx;
    // margin: 0 24rpx;
  }

  // tab栏容器
  .tabs-content {
    background-color: #fff;
    transition: all 0.2s;
    margin: 0 auto;
  }
  .tab-sticky {
    width: 702rpx;
    margin: 0 auto;

    // position: sticky;
    z-index: 9;
  }

  //商品列表的内容
  .goods-list {
    flex: 1;
    margin: 0 auto;
    background-color: #fff;
    transition: all 0.2s;

    .swiper-box {
      width: 702rpx;
      height: 100%;
      margin: 0 auto;
      background-color: #fff;
    }

    .list-cell {
      background-color: #fff;
      border-bottom: 2rpx solid #eeeeee;

      view {
        line-height: 70rpx;
        width: 100%;
        font-size: 30rpx;
        text-indent: 25rpx;
      }
    }
  }
}

.swiper-item {
  height: 100%;
}

//寻配件列表
@mixin icon-xun() {
  width: 36rpx;
  height: 36rpx;
  background: #fbb000;
  color: #fff;
  border-radius: 4rpx;
  padding: 0rpx 4rpx;
  font-size: 32rpx;
}

$colorEB5C02: #eb5c02;
</style>
